package com.dpj.exercise;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Random;
import java.util.Vector;

@Slf4j(topic = "c. ExerciseSell")
public class ExerciseSell {
    @SneakyThrows
    public static void main(String[] args) {
        //模拟多人买票
        TicketWindow window=new TicketWindow(1000);
        //卖出的票数统计
        List<Integer> amountList=new Vector<>();

        //所有线程的集合
        List<Thread> threadList=new Vector<>();
        for (int i = 0; i <4000 ; i++) {
            Thread thread = new Thread(()->{
                //买票
              int count=window.sell(randomAmount());
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                amountList.add(count);

            });
            thread.start();
            threadList.add(thread);
        }
        for (Thread thread : threadList) {
            thread.join();
        }
        //统计剩余票数
        log.debug("余票：{}",window.getCount());
        //统计售出票数
        log.debug("卖出的票数：{}",amountList.stream().mapToInt(i->i).sum());
    }

    //random为线程安全
    static Random random=new Random();
    //随机1-5
    public static int randomAmount(){
        return  random.nextInt(5)+1;
    }
}

//售票窗口
class   TicketWindow{
    private int count;
    public TicketWindow(int count){
        this.count=count;
    }
    //获取余票数量
    public int getCount(){
        return count;
    }
    //售票
    public synchronized int sell(int amount) {
        if (this.count >= amount) {
            this.count-=amount;
            return amount;
        }
        else {
            return 0;
        }
    }
}
